package com.example.helloxml;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Adapter;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;

public class MainActivity extends Activity {

	private List<Student> mStudentList;
	private ListView mStudents;
	private Button mBtn;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		mStudents = (ListView)findViewById(android.R.id.list);
		mBtn = (Button)findViewById(R.id.btn);
		mBtn.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				pullParse();
				ListAdapter adapter = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_1, mStudentList);
				mStudents.setAdapter(adapter);
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	private void domParse(){
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			InputStream is =getResources().getAssets().open("student.xml");
			Document document = builder.parse(is);
			Element root = document.getDocumentElement();
			NodeList nodes = root.getElementsByTagName("student");
			mStudentList = new ArrayList<Student>();
			for(int i = 0;i<nodes.getLength();i++){
				Student student = new Student();
				Element studentElement = (Element)nodes.item(i);
				student.setId(Integer.parseInt(studentElement.getAttribute("id")));
				String name = studentElement.getElementsByTagName("name").item(0).getFirstChild().getNodeValue();
				int age = Integer.parseInt(studentElement.getElementsByTagName("age").item(0).getFirstChild().getNodeValue());
				student.setAge(age);
				student.setName(name);
				Log.i("Name", "---------->" + student.getName());
				mStudentList.add(student);
			}
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	private void saxParse(){
		
		try {
			SAXParserFactory factory = SAXParserFactory.newInstance();
			SAXParser parser = factory.newSAXParser();
			MyHandler handler = new MyHandler();
			InputStream is =getResources().getAssets().open("student.xml");
			parser.parse(is, handler);
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private void pullParse(){
		XmlPullParserFactory factory;
		try {
			factory = XmlPullParserFactory.newInstance();
			XmlPullParser xmlPull = factory.newPullParser();
			InputStream is =getResources().getAssets().open("student.xml");
			xmlPull.setInput(is, "UTF-8");
			int eventCode = xmlPull.getEventType();
			Student currentStudent = null;
			while(eventCode!=XmlPullParser.END_DOCUMENT){
				switch(eventCode){
				case XmlPullParser.START_DOCUMENT:
					 mStudentList = new ArrayList<Student>();
					 break;
				case XmlPullParser.START_TAG:
					String tagName = xmlPull.getName();
					if(tagName.equalsIgnoreCase("student")){
						currentStudent = new Student();
						currentStudent.setId(Integer.parseInt(xmlPull.getAttributeValue(null,"id")));
					}else if(currentStudent!=null){
						if(tagName.equalsIgnoreCase("name")){
							currentStudent.setName(xmlPull.nextText());
							Log.i("Name", "---------->" + currentStudent.getName());
						}else if(tagName.equalsIgnoreCase("age")){
							currentStudent.setAge(Short.parseShort(xmlPull.nextText()));
						}
					}
					break;
				case XmlPullParser.END_TAG:
					if(currentStudent!=null&&xmlPull.getName().equalsIgnoreCase("student")){
						mStudentList.add(currentStudent);
						currentStudent = null;
					}
					break;
				}
				eventCode = xmlPull.next();
			}
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	private class MyHandler extends DefaultHandler{
		
		private StringBuilder sb;
		private Student student;
		@Override
		public void startDocument() throws SAXException {
			// TODO Auto-generated method stub
			super.startDocument();
			mStudentList = new ArrayList<Student>();
			sb = new StringBuilder();
		}
		
		@Override
		public void startElement(String uri, String localName, String qName,
				Attributes attributes) throws SAXException {
			// TODO Auto-generated method stub
			super.startElement(uri, localName, qName, attributes);
			if(localName.equals("student")){
				student = new Student();
				student.setId(Integer.parseInt(attributes.getValue("id")));
			}
			sb.setLength(0);
		}
		@Override
		public void characters(char[] ch, int start, int length)
				throws SAXException {
			// TODO Auto-generated method stub
			super.characters(ch, start, length);
			sb.append(ch,start,length);
		}
		
		@Override
		public void endElement(String uri, String localName, String qName)
				throws SAXException {
			// TODO Auto-generated method stub
			super.endElement(uri, localName, qName);
			if(localName.equalsIgnoreCase("name")){
				student.setName(sb.toString());
				Log.i("Name", "---------->" + student.getName());
			}else if(localName.equalsIgnoreCase("age")){
				student.setAge(Integer.parseInt(sb.toString()));
			}else if(localName.equalsIgnoreCase("student")){
				mStudentList.add(student);
			}
		}
		
		@Override
		public void endDocument() throws SAXException {
			// TODO Auto-generated method stub
			super.endDocument();
		}
	} 
	
	
}
